package com.ionehe.cola.common.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 时间工具类
 *
 * @author 2022/1/24 <a href="mailto:a@ionehe.com">skedison</a>
 */
public class DateUtil {
    private DateUtil() {
        throw new IllegalStateException("Utility class");
    }

    public static boolean isToday(long time) {
        return isThisTime(time, "yyyy-MM-dd");
    }

    public static boolean isThisWeek(long time) {
        Calendar calendar = Calendar.getInstance();

        int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);

        calendar.setTime(new Date(time));

        int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);

        return paramWeek == currentWeek;
    }

    public static boolean isThisMonth(long time) {
        return isThisTime(time, "yyyy-MM");
    }

    private static boolean isThisTime(long time, String pattern) {
        Date date = new Date(time);

        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        String param = sdf.format(date);
        String now = sdf.format(new Date());

        return param.equals(now);
    }

    public static Date timestamp2Date(String time) {
        Timestamp ts = new Timestamp(Long.parseLong(time));
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return dateFormat.parse(dateFormat.format(ts));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前时间前()天
     *
     * @param subSize 天数
     * @return MM月dd日的日期集合
     */
    private static List<String> getFormatSubDate(int subSize) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日");

        Calendar instance = Calendar.getInstance();

        instance.setTime(new Date());
        instance.add(Calendar.DATE, -subSize + 1);

        return Stream.iterate(instance.getTime(), date -> dateIncr(date))
                .limit(subSize)
                .map(dateFormat::format)
                .collect(Collectors.toList());
    }

    private static Date dateIncr(Date date) {
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        instance.add(Calendar.DATE, 1);
        return instance.getTime();
    }
}
